<?php

namespace app\admin\logic;
use app\admin\logic\BasicLogic;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use app\common\service\ShunfengApiService;
use app\order\logic\OrderWhLogic;

class TrackLogic extends BasicLogic
{

    /**
     * @desc 顺丰自发货运单号回传地址
     * @date 2024-04-28
     * @author luckyXiong
     */
    public function sfOrderBack($post=[]){
        htmlLog(['data'=>$post],OPERATE_LOG . date('Ym') . '/sfOrderBack/' . date('Ymd') . '.txt');
        $order_id     = $post['refNo1']??'';
        $track_number = $post['deliveryNo']??'';
        $order_status = $post['orderStatus']??'';
        $check_res = strpos($order_id, '-1');


        if ($order_status == 11 || $check_res != false) {
            return $this->jsonMessage(0,true,'操作成功');
        }


        if ($order_status != 9 || empty($order_id) || empty($track_number) || strlen($track_number) < 10) {
            return $this->jsonMessage(1,false,'参数错误');
        }

        //update 2024-05-23  处理网红订单逻辑;
        $pattern      = '/^2/';
        $is_wh_order  = preg_match($pattern, $order_id);
        if($is_wh_order){
            self::update_sf_wh($order_id,$track_number);
            return $this->jsonMessage(0,true,'操作成功');
        }

        //update 2024-05-31  官方面单的不处理;
        $order_shipping = Db::name('order')->where('order_id',$order_id)->value('shipping_type');

        if($order_shipping=='TIKTOK'){
            return $this->jsonMessage(0,true,'操作成功');
        }

        //USPS
        $delivery_option_id = preg_match("/^9\d{9,}$/", $track_number) ? '7117858858072016686' : '7117859084333745966';
        $shop_id = Db::name('order')->where('order_id',$order_id)->value('shop_id');
        $old_tracking    =  Db::name('order_ship')->where('order_id', $order_id)->find();
        $exist_ship      =  Db::name('order_ship')->where('order_id', $order_id)->find();

        if (preg_match("/^(9\d{9,}|1Z.{12,})$/", $track_number)){
            //推送回传单号到tik
            $info = [
                'order_id'             =>$order_id,
                'shop_id'              =>$shop_id,
                'tracking_number'      =>$track_number,
                'shipping_provider_id' =>$delivery_option_id,
            ];
            $res  =(new ShunfengApiService())->order_tracking_number_sf_back($info);
            htmlLog(['response'=>$res],OPERATE_LOG . date('Ym') . '/sfOrderBack/' . date('Ymd') . '.txt');
            if(isset($res['message'])&& in_array($res['message'],['Success','package already rts','already rts'])){
                $Message         = '顺丰物流单号回传完成';
                $status          = 4;
                $tracking_number = $track_number;
                $code            = 4;
                //更新订单主表
                Db::name('order')->where('order_id', $order_id)->update([
                    'status'              => 'AWAITING_COLLECTION',
                    'tracking_number'     =>  $track_number,
                ]);

                // update 2024-06-29 发送type=3消息给用户物流单号;
                self::send_track_number($order_id,$shop_id,$track_number);

            }else{
                $Message         = '同步发货状态失败';
                $status          = 2;
                $tracking_number = $track_number;
            }
           if($exist_ship){
               Db::name('order_ship')->where('order_id', $order_id)->update([
                   'status'              => $status,
                   'tracking_number'     => $tracking_number,
                   'msg'                 => $Message,
                   'time'                => time()
               ]);
           }
            return $this->jsonMessage(0,true,'操作成功');
        } else {
            $Message           = '物流单号生成中';
            $status            = 2;
            $tracking_number   = $old_tracking['tracking_number']??'';
            if($exist_ship){
                Db::name('order_ship')->where('order_id', $order_id)->update([
                    'status'              => $status,
                    'tracking_number'     => $tracking_number,
                    'msg'                 => $Message,
                    'time'                => time()
                ]);
            }
            return $this->jsonMessage(1,false,'正则验证失败',[]);
        }
    }



    /**
     * @desc   网红订单物流单号处理
     * @author xx
     * @date   2024-05-23
     */
    public function update_sf_wh($order_id,$track_number){
        Db::name('orderwh')->where('order_id', $order_id)->update([
            'tracking_beforehand' => 4,
            'tracking_number'     => $track_number,
            'msg'                 => '顺丰物流单号回传完成',
            'updatetime'          => time()
        ]);
        $return['code']        = 4;
        $return['shop_id']     = '';
        $return['order_id']    = $order_id;
        $return['msg']    =  '顺丰物流单号回传完成';
        $return['data']   = $track_number;
        OrderWhLogic::insertOrderWhLog($return);
    }


    /**
     * @desc   发送物流单号消息给用户
     * @author luckyXiong
     * @date   2024-06-29
     */
    public function send_track_number($order_id,$shop_id,$track_number){
        htmlLog(['order_id'=>$order_id,'shop_id'=>$shop_id,'track_number'=>$track_number],OPERATE_LOG . date('Ym') . '/send_track_number/' . date('Ymd') . '.txt');
        if(!$track_number)     return '';
        // todo 消息数据推送到队列执行
        MqTaskPushLogic::mq_task_push(
            '',
            MqQueueName::QUEUE_PRIVATE_SEND_MESSAGE_QUEUE,
            [
                'shop_id'        => $shop_id,
                'order_id'       => $order_id,
                'type'           => 3,
                'text'           => $track_number,
            ],
            false
        );


    }











}